//
//  OAuthController.swift
//  weibo001
//
//  Created by ios on 15/11/5.
//  Copyright © 2015年 ios. All rights reserved.
//

import UIKit

class OAuthController: UIViewController {
    
     private lazy var webView = UIWebView()
    
    
    
    
//关闭登录控制器
    
    @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }

// 自动填充用户名密码
    @objc private func autoFill() {
    
        let js = "document.getElementById('userId').value = 'daoge10000@sina.cn';" +
        "document.getElementById('passwd').value = 'qqq123';"
        
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    
    }

 //创建视图
    override func loadView() {
       // super.loadView()
        
        view = webView
      webView.delegate = self
        
       // view.backgroundColor = UIColor.redColor()
        title = "登录微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }
    
//加载网页页面
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.webView.loadRequest(NSURLRequest(URL: NetworkTool.sharedTools.oauthURL))
        
    }
    
}


extension  OAuthController: UIWebViewDelegate {

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //判断访问的的主机地址是不是百度，如果是百度就不加载
        
        guard  let url = request.URL where url.host == "www.baidu.com" else{
        
        return true
        }
        
//        print(url.query)
//       print(url.host)
    //    url.query?.hasPrefix("code=")
        //判断从百度地址的url中提取的"code="是否存在
        guard let query = url.query where query.hasPrefix("code=") else {
        
        
          return false
        }
        
        //提取code
    
        let code = query.substringFromIndex("code=".endIndex)
        print(query)
        print("授权码是"+code)
        
        
        
        //加载  accessToken

       UserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccessed) -> () in
        // finished 的完整代码
        if !isSuccessed {
            print("失败了")
        } else {
          print("成功了")
            print(UserAccountViewModel.sharedUserAccount.account)
            
           self.dismissViewControllerAnimated(false, completion: { () -> Void in
            NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "welcome")
           })
            
            
            
        }

    }
        
       
       return false
    }
  
    
}


























